package cn.kgc.jdbc.service;

import cn.kgc.jdbc.entity.User;
import cn.kgc.jdbc.util.JDBCUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author: mosin
 * @version: v1.0  2022/8/25
 *演示用户的登录和注册操作
 *
 */
public class UserService {

    // 用户登录
    public  Boolean login(User user){
        //根据用户信息 查询数据库  1.数据库中存在用户信息 登录成功    jdbc查询数据库
        // 获取连接
        Connection connection = JDBCUtil.getConnection();
        Statement statement = null;
        ResultSet resultSet = null;
        try {
             statement = connection.createStatement();
            String sql = "select *  from user where username= '"+user.getUsername()+"' and password = '"+user.getPassword()+"'";
            System.out.println("sql = " + sql);
            resultSet = statement.executeQuery(sql);
            return  resultSet.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JDBCUtil.closeAll(connection, statement, resultSet);
        }
        return  false;
    }

    // 用户注册
    public  Boolean register(User user){

        Connection connection = JDBCUtil.getConnection();
        try {
            Statement statement = connection.createStatement();
            String sql = "insert into user(username,password)values('"+user.getUsername()+"','"+user.getPassword()+"')";
            System.out.println("sql = " + sql);
            int i = statement.executeUpdate(sql);
            return  i>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return  false;
    }

}
